<?php

/**
 * Gestisce i risultati di un'oggetto Syrius_Adapter_Query
 * @package Adapter
 * @author <domenico.biancardi@gmail.com>
 */

namespace Syrius\Adapter;

class Result extends \Mysqli_Result implements \Iterator, \Countable {
	private $_pointer = 0;

	/**
	 * Recupera un'oggetto
	 * @return NULL|object
	 */
	public function fetchObject() {
		if (!$row = $this->fetch_object()) {
			return NULL;
		}
		return $row;
	}

	/**
	 * Recupera un'array
	 * @return NULL|array:
	 */
	public function fetchAssocArray() {
		if (!$row = $this->fetch_assoc()) {
			return NULL;
		}
		return $row;
	}

	/**
	 * @return NULL|mixed
	 */
	public function fetchNumArray() {
		if (!$row = $this->fetch_row()) {
			return NULL;
		}
		return $row;
	}

	public function fetchAll($type = MYSQL_ASSOC) {
		if ($type !== MYSQLI_ASSOC and $type !== MYSQLI_NUM and $type !== MYSQLI_BOTH) {
			$type = MYSQLI_ASSOC;
		}
		if (!$rows = $this->fetch_all($type)) {
			return NULL;
		}
		return $rows;
	}

	public function fetchFieldsInfo() {
		if (!$fieldsInfo = $this->fetch_fields()) {
			throw new Exception ('No information available for table fields.');
		}
		return $fieldsInfo;
	}

	public function fetchFieldInfo() {
		if (!$fieldInfo = $this->fetch_field()) {
			throw new Exception ('No information available for current table field.');
		}
		return $fieldInfo;
	}

	public function movePointer($offset) {
		$offset = abs(( int )$offset);
		$limit = $this->num_rows - 1;
		if ($limit <= 0 or $offset > $limit) {
			return FALSE;
		}
		unset ($limit);
		return $this->data_seek($offset);
	}

	public function count() {
		return $this->num_rows;
	}

	public function rewind() {
		$this->_pointer = 0;
		$this->movePointer($this->_pointer);
		return $this;
	}

	public function current() {
		return $this->fetchObject();
	}

	public function key() {
		return $this->_pointer;
	}

	public function next() {
		++$this->_pointer;
		return $this;
	}

	public function valid() {
		return $this->_pointer < $this->num_rows;
	}

	public function __destruct() {
		$this->close();
	}

	public function __construct($sql) {
		parent::__construct($sql->getDriver());
		$this->_pointer = 0;
	}

}

?>
